<template>
  <div class="main-container">
    <div class="main" ref="containerRef"></div>
    <div class="tip" ref="tipRef">
      <div class="title">
        <span class="shine-text">{{ current.name }}</span>
      </div>
      <div class="info-item">
        <div class="name">专卖店数量：</div>
        <div class="value">{{ current.brandStoreNumber }}</div>
      </div>
      <div class="info-item">
        <div class="name">经销商数量：</div>
        <div class="value">{{ current.dealerNumber }}</div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref } from "vue";
import * as echarts from "echarts";
import "echarts-gl";

const chinaJson = require("@/assets/mapJson/china.json");
const chinaMapBg = require("@/assets/images/map/china-map-bg2.png");
const mapOrigin = require("@/assets/images/map/mapOrigin.png");
const mapEndPoint = require("@/assets/images/map/mapEndPoint.png");
const containerRef = ref(null);
const tipRef = ref(null);
const jsonData = ref({});
const current = ref({});
const getJsonData = async () => {
  try {
    const res = await fetch("/json/map-api.json");
    jsonData.value = await res.json(); // 解析 JSON 格式
  } catch (err) {
    console.error("读取失败：", err);
  }
};
const initEchart = () => {
  const myChart = echarts.init(containerRef.value);
  echarts.registerMap("china", chinaJson);
  const nkSite = [114.765044, 25.661369];
  const echartsData = jsonData.value.chinaMap.echartsData;

  let scatterData = [];
  const linesData = echartsData.map((item) => {
    scatterData.push({
      value: item.site,
    });
    return {
      coords: [nkSite, item.site], // 数组中顺序表示箭头方向
    };
  });
  scatterData.push({
    value: nkSite,
    symbol: "image://" + mapEndPoint,
    symbolSize: 100,
  });
  // console.log("scatterData", scatterData);

  const option = {
    geo: {
      map: "china",
      aspectScale: 1, //长宽比
      zoom: 1.1,
      roam: false,
      itemStyle: {
        areaColor: {
          type: "radial",
          x: 0.5,
          y: 0.5,
          r: 0.8,
          colorStops: [
            {
              offset: 0,
              color: "#09132c", // 0% 处的颜色
            },
            {
              offset: 1,
              color: "#274d68", // 100% 处的颜色
            },
          ],
        },
        shadowColor: "RGBA(179, 242, 253, 0.6)",
        borderWidth: 2,
        shadowOffsetX: 0,
        shadowOffsetY: 6,
      },
      regions: [
        {
          name: "南海诸岛",
          itemStyle: {
            areaColor: "rgba(0, 10, 52, 1)",
            borderColor: "rgba(0, 10, 52, 1)",
            opacity: 0,
            label: {
              show: false,
              color: "#009cc9",
            },
          },
        },
      ],
    },
    series: [
      {
        type: "map",
        map: "china",
        zoom: 1.1,
        aspectScale: 1,
        itemStyle: {
          areaColor: {
            image: chinaMapBg,
            repeat: "no-repeat",
          },
          borderColor: "RGBA(179, 242, 253, 1)",
          borderWidth: 2,
          shadowColor: "rgba(0, 0, 0, 0.5)",
          shadowBlur: 10,
        },
        data: [],
      },
      {
        type: "lines",
        zlevel: 2,
        effect: {
          show: true,
          period: 4, //箭头指向速度，值越小速度越快
          trailLength: 0.4, //特效尾迹长度[0,1]值越大，尾迹越长重
          symbol: "arrow", //箭头图标
          symbolSize: 5,
        },
        lineStyle: {
          color: "RGBA(220, 225, 26, 1)",
          width: 1, //线条宽度
          opacity: 0.1, //尾迹线条透明度
          curveness: 0.3, //尾迹线条曲直度
          type: "dashed",
        },
        data: linesData,
      },
      {
        type: "scatter",
        coordinateSystem: "geo",
        symbol: "image://" + mapOrigin,
        symbolSize: 80,
        zlevel: 3,
        data: scatterData,
      },
    ],
  };
  myChart.setOption(option);
  // 当前轮播索引
  let i = 0;
  // 是否暂停自动轮播
  let isPaused = false;

  // 显示提示框的函数
  const showTip = () => {
    if (isPaused) return; // 被暂停时不执行

    if (i < 0 || i >= echartsData.length) {
      i = 0;
    }

    // 获取当前点数据
    const point = echartsData[i];
    // 检查point是否存在
    if (!point) {
      console.error("未找到有效的坐标点数据");
      return;
    }
    // console.log("point", point);

    current.value = point;
    // 确保coord存在
    if (!point.site) {
      console.error("坐标点数据缺少site属性");
      return;
    }

    const pos = myChart.convertToPixel("geo", point.site);

    const tip = tipRef.value;
    if (tip && pos) {
      tip.style.left = pos[0] - 60 + "px";
      tip.style.top = pos[1] - 100 + "px";
      tip.style.display = "block";
    }

    i = (i + 1) % echartsData.length;
  };
  let timer = null;
  // 启动自动轮播
  const startAutoPlay = () => {
    if (timer) clearInterval(timer);
    timer = setInterval(showTip, jsonData.value.chinaMap.cutTime);
  };

  // 恢复自动轮播（3秒后）
  const resumeAutoPlay = () => {
    setTimeout(() => {
      if (isPaused) {
        isPaused = false;
        startAutoPlay();
      }
    }, 3000); // 3秒后恢复
  };

  // 初始显示第一个
  showTip();
  startAutoPlay();

  // 点击事件处理
  myChart.on("click", (params) => {
    console.log("params", params);

    // 优先处理散点点击
    if (params.seriesType === "scatter" && params.data && params.data.value) {
      const coord = params.data.value;
      const match = echartsData.find(
        (item) =>
          Math.abs(item.site[0] - coord[0]) < 0.001 &&
          Math.abs(item.site[1] - coord[1]) < 0.001
      );

      if (match) {
        current.value = match;
        const pos = myChart.convertToPixel("geo", match.site);
        const tip = tipRef.value;
        if (tip && pos) {
          tip.style.left = pos[0] - 60 + "px";
          tip.style.top = pos[1] - 100 + "px";
          tip.style.display = "block";
        }

        // 暂停轮播
        if (!isPaused) {
          isPaused = true;
          if (timer) {
            clearInterval(timer);
            timer = null;
          }
          resumeAutoPlay();
        }
      }
      return;
    }

    // 处理地图区域点击（可选）
    if (params.seriesType === "map" && params.name) {
      const match = echartsData.find((item) => item.name === params.name);
      if (match) {
        current.value = match;
        const pos = myChart.convertToPixel("geo", match.site);
        const tip = tipRef.value;
        if (tip && pos) {
          tip.style.left = pos[0] - 60 + "px";
          tip.style.top = pos[1] - 100 + "px";
          tip.style.display = "block";
        }

        if (!isPaused) {
          isPaused = true;
          if (timer) {
            clearInterval(timer);
            timer = null;
          }
          resumeAutoPlay();
        }
      }
    }
  });
};
onMounted(async () => {
  await getJsonData();
  initEchart();
});
</script>
<style lang="less" scoped>
.main-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  .main {
    width: 1000px;
    height: 400px;

    margin: 0 auto;
    // transform: scale(0.8, 0.8);
  }
  .tip {
    position: absolute;
    box-sizing: border-box;
    padding: 8px 12px;
    display: none;
    background: url("~@/assets/images/map/dialogBg.png") no-repeat;
    background-size: 100% 100%;
    pointer-events: none; // 防止弹框影响鼠标事件
    z-index: 10;

    .title {
      font-size: 20px;
      font-weight: bold;
      padding: 3px 0px;
      .shine-text {
        color: rgba(255, 255, 255, 0.7);
      }
    }

    .info-item {
      margin-top: 3px;
      display: flex;
      justify-content: flex-start;
      align-items: center;

      .name {
        color: rgba(255, 255, 255, 0.7);

        font-size: 18px;
      }
      .value {
        color: rgba(255, 255, 255, 0.7);
        font-size: 20px;
      }
    }
  }
}
</style>
